package com.macro.mall.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.dto.ProductSyncRequest;
import com.macro.mall.model.PmsProduct;
import com.macro.mall.model.StoreQueryParam;
import com.macro.mall.model.XhsStore;
import com.macro.mall.model.request.PlaceQueryRequest;
import com.macro.mall.model.response.*;
import com.macro.mall.model.vo.store.XhsStoreVo;
import com.macro.mall.service.PoiFacilityService;
import com.macro.mall.service.PmsProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Controller
@Api(tags = "XhsStoreController")
@Tag(name = "XhsStoreController", description = "门店管理")
@RequestMapping("/poi/facility")
public class XhsStoreController {

    private static final Logger logger = LoggerFactory.getLogger(XhsStoreController.class);

    @Resource
    private PoiFacilityService poiFacilityService;

    @Resource
    private PmsProductService pmsProductService;


    @GetMapping("/listAll")
    public FacilityListResponse listAllFacilityTags() {
        return poiFacilityService.getAllFacilityTags();
    }


    @ApiOperation("分页查询门店信息")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public XhsBaseResponse<PoiListData> getPoiList(
            @RequestParam(required = false, defaultValue = "1") Integer pageNo,
            @RequestParam(required = false, defaultValue = "100") Integer pageSize) throws Exception {
        return poiFacilityService.getPoiList(pageNo, pageSize);
    }


    @ApiOperation("保存所有门店信息并同步商品")
    @RequestMapping(value = "/saveStoreDB", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<Boolean> saveStoreDB(){
        try {
            logger.info("开始同步门店信息...");
            // 1. 保存门店信息
            poiFacilityService.saveStoreDB();
            logger.info("门店信息同步完成");
            
            logger.info("开始同步商品信息...");
            // 2. 同步所有未删除的商品
            syncAllActiveProducts();
            logger.info("商品信息同步完成");
            
            return CommonResult.success(true, "门店和商品信息同步完成");
        } catch (Exception e) {
            logger.error("同步过程中发生错误", e);
            return CommonResult.failed("同步失败：" + e.getMessage());
        }
    }

    /**
     * 同步所有未删除的商品
     */
    private void syncAllActiveProducts() {
        try {
            // 查询所有未删除的商品 (delete_status = 0)
            List<PmsProduct> activeProducts = pmsProductService.listActiveProducts();
            
            logger.info("找到 {} 个未删除商品需要同步", activeProducts.size());
            
            int successCount = 0;
            int failCount = 0;
            
            // 循环调用商品同步
            for (PmsProduct product : activeProducts) {
                try {
                    ProductSyncRequest request = new ProductSyncRequest(Math.toIntExact(product.getId()));
                    Boolean result = pmsProductService.syncProduct(request);
                    
                    if (result != null && result) {
                        successCount++;
                        logger.debug("商品 {} (名称: {}) 同步成功", product.getId(), product.getName());
                    } else {
                        failCount++;
                        logger.warn("商品 {} (名称: {}) 同步失败", product.getId(), product.getName());
                    }
                } catch (Exception e) {
                    failCount++;
                    logger.error("商品 {} (名称: {}) 同步过程中发生异常: {}", product.getId(), product.getName(), e.getMessage());
                }
            }
            
            logger.info("商品同步完成，成功: {}, 失败: {}", successCount, failCount);
        } catch (Exception e) {
            logger.error("同步商品时发生错误", e);
            throw new RuntimeException("商品同步失败", e);
        }
    }



    @ApiOperation("获取城市列表")
    @RequestMapping(value = "/getCityList", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<String>> getCityList(){
        List<String> cityList =   poiFacilityService.getCityList();
        return CommonResult.success(cityList);
    }




    @ApiOperation("查询可用地点")
    @RequestMapping(value = "/selStore", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<List<XhsStoreVo>> selStore(@RequestBody StoreQueryParam storeQueryParam ) throws Exception {
        List<XhsStoreVo> stores = poiFacilityService.selStore(storeQueryParam);
        return CommonResult.success(stores);
    }




    @ApiOperation("根据经纬度查询当前地区")
    @RequestMapping(value = "/selCity", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> selCity(@RequestBody StoreQueryParam storeQueryParam ) throws Exception {
        String city = poiFacilityService.selCity(storeQueryParam);
        return CommonResult.success(city);
    }




    @ApiOperation("查询可用地点")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @ResponseBody
    public PlaceQueryResponse queryPlaces(@RequestBody PlaceQueryRequest request) throws Exception {
        return poiFacilityService.queryPlaces(request);
    }


    @GetMapping("/productListByPoi")
    public PoiProductListResponse getProductsByPoi(@RequestParam String poiId) throws Exception {
        return poiFacilityService.getProductsByPoi(poiId);
    }

    @ApiOperation("导入Excel更新门店手机号")
    @RequestMapping(value = "/importStorePhone", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Map<String, Integer>> importStorePhone(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return CommonResult.failed("上传文件为空");
            }
            
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return CommonResult.failed("请上传Excel文件(.xlsx或.xls格式)");
            }
            
            Map<String, Integer> result = poiFacilityService.importStorePhoneFromExcel(file);
            return CommonResult.success(result, "导入完成，成功" + result.get("success") + "条，失败" + result.get("fail") + "条");
        } catch (Exception e) {
            return CommonResult.failed("导入失败：" + e.getMessage());
        }
    }
}
